import store from "../store/index.js"

//请求后端接口的根路径
let baseUrl = "/dpc";


//如果是微信小程序走此代码
// #ifdef MP-WEIXIN || MP-QQ
baseUrl = "http://192.168.31.201:7245"
// #endif		

/**
 * 发送一个post请求给后端
 * @param {Object} url 请求的路径
 * @param {Object} data 请求的数据
 */
async function PostAsync(url, data) {
	
	let response = {
		Code: "",
		Data: "",
		Msg: "",
		Success: true,
	};
	let header = {};
	if (store.getters.token) {
		header = {
			"Authorization": `Bearer ${store.getters.token}`
		};
	}
	await Request({
			url: baseUrl + url,
			data: data,
			method: "POST",
			header: header,
			dataType: 'json'
		}).then(res => {
			response.Success = res.Success;
			response.Msg = res.Msg;
			response.Code = res.Code;
			response.Data = res.Data;
		})
		.catch(err => {
			response.Success = false;
			response.Msg = err;
		})

	return response;

}
/**
 * 发送一个post请求给后端 并且返回上一个页面
 * @param {Object} url 请求的路径
 * @param {Object} data 请求的数据
 */
async function PostReturnPage(url, body) {
	let response = await PostAsync(url, body);
	let {
		success,
		data,
		message
	} = response;
	if (success) {
		uni.showToast({
			icon: "none",
			title: "操作成功",
			duration: 1500
		})
		setTimeout(() => {
			uni.navigateBack({
				delta: 1
			})
		}, 1500)
	} else {
		uni.showToast({
			icon: "error",
			title: message,
			duration: 1500
		})
	}
	return response;

}




var Request = function(option) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: option.url,
			data: option.data,
			method: option.method,
			header: option.header,
			dataType: option.dataType,
			success: async (res) => {
				
				if (res.statusCode == 404) {
					uni.showToast({
						icon: "none",
						duration: 3000,
						title: "请求的资源不存在404!",
					})
					reject("请求的资源不存在404!");
				} else if (res.statusCode == 500) {
					uni.showToast({
						icon: "none",
						duration: 3000,
						title: "服务后端出小差了!",
					})
					reject("服务后端出小差了!");
				} else if (res.statusCode == 200) {
					let {
						data: {
							Code,
							Msg,
							Success
						}
					} = res;

					if (Code == "401") {
						//如果没有授权 直接丢弃当前Token
						await store.dispatch("TokenLose", {});
						reject("你没有权限访问")
					}
					else if(Code=="500")
					{
						uni.showToast({
							icon: "none",
							duration: 3000,
							title: Msg,
						})
						reject(Msg)
					}

					resolve(res.data);
				}
			},
			fail: (err) => {
				console.log(err)
				reject(err);
			}
		});
	})
}

var Upload = function(filePath) {
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: baseUrl + "/Resources/BatchUpload",
			filePath: filePath,
			name: 'file',
			success: (uploadFileRes) => {
				
				resolve(JSON.parse(uploadFileRes.data));
			}
		});
	});
}



module.exports = {
	PostAsync,
	Upload,
	PostReturnPage
}